const Multer = require('koa-multer')
const path = require('path')
const Jimp = require('jimp')

const {AVATAR_PATH,PICTURE_PATH} = require('../constants/file_path')

const storage1 = Multer.diskStorage({
  destination:(req,file,cb)=>{
    cb(null,AVATAR_PATH)
  },
  filename:(req,file,cb)=>{
    cb(null,Date.now()+path.extname(file.originalname)) 
    //file:上传文件的信息 file.originalname:原始文件的名字 path.extname:取出后缀名
  }
})

const storage2 = Multer.diskStorage({
  destination:(req,file,cb)=>{
    cb(null,PICTURE_PATH)
  },
  filename:(req,file,cb)=>{
    cb(null,Date.now()+path.extname(file.originalname)) 
    //file:上传文件的信息 file.originalname:原始文件的名字 path.extname:取出后缀名
  }
})

const avatarUpload = Multer({
  storage:storage1
})
const avatarHandle = avatarUpload.single('avatar')

const pictureUpload = Multer({
  storage:storage2
})
const pictureHandle = pictureUpload.array('picture',9)

const pictureResize = async (ctx,next)=>{
  // 获取所有的图像
  const files = ctx.req.files
  // 遍历处理图像
  for(let file of files){
    const destPath = path.join(file.destination,file.filename)
    Jimp.read(file.path).then(image=>{
      image.resize(1280,Jimp.AUTO).write(`${destPath}-large`)
      image.resize(640,Jimp.AUTO).write(`${destPath}-middle`)
      image.resize(320,Jimp.AUTO).write(`${destPath}-small`)
    })
  }
  await next()
}

module.exports = {avatarHandle, pictureHandle, pictureResize}